import { DataSource, DataSourceOptions } from 'typeorm';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';

export function getEnv(env: string): Record<string, string> | undefined {
    if (fs.existsSync(env)) {
        const envFile = fs.readFileSync(env);
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-assignment
        const parsed = dotenv.parse(envFile);
        return parsed as Record<string, string>;
    }
}

export function buildConnectionOptions() {
    const defaultConfig = getEnv('.env');
    const envConfig = getEnv(`.env.${process.env.NODE_ENV || 'development'}`);
    const config = { ...defaultConfig, ...envConfig };
    console.log('config', config);
    return {
        type: config['DB_TYPE'],
        host: config['DB_HOST'],
        port: config['DB_PORT'],
        username: config['DB_USERNAME'],
        password: config['DB_PASSWORD'],
        database: config['DB_DATABASE'],
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: Boolean(config['DB_SYNC']),
        autoLoadEntities: Boolean(config['DB_AUTOLOAD']),
    } as TypeOrmModuleOptions;
}

export default new DataSource({
    ...buildConnectionOptions(),
} as DataSourceOptions);
